import json
import requests

biz = "MzA5NzE0Mjg4Ng=="
album_id = "3569278968102551558"
base_url = "https://mp.weixin.qq.com/mp/appmsgalbum"

def fetch_wechat_articles():
    # 初始化数据集合
    all_articles = []
    session = requests.Session()
    
    def make_request(params):
        try:
            resp = session.get(
                base_url,
                params={**params, "__biz": biz, "album_id": album_id, "f": "json"},
                timeout=10
            )
            resp.raise_for_status()
            return resp.json()
        except Exception as e:
            print(f"Request failed: {e}")
            return None

    # 初始请求
    initial_data = make_request({"action": "getalbum"})
    if not initial_data:
        return

    # 提取第一页数据
    articles = initial_data.get("getalbum_resp", {}).get("article_list", [])
    all_articles.extend(articles)
    print(f"Initial articles fetched: {len(articles)}")

    # 获取分页参数
    last_article = articles[-1] if articles else None
    msgid = last_article.get("msgid") if last_article else None
    itemidx = last_article.get("itemidx") if last_article else None

    # 分页请求
    while msgid and msgid != "null":
        params = {
            "action": "getalbum",
            "count": 10,
            "begin_msgid": msgid,
            "begin_itemidx": itemidx
        }
        
        page_data = make_request(params)
        if not page_data:
            break

        new_articles = page_data.get("getalbum_resp", {}).get("article_list", [])
        if not new_articles:
            break

        if type(new_articles) != list:
            new_articles = [new_articles]

        all_articles.extend(new_articles)
        print(f"Fetched {len(new_articles)} new articles, total: {len(all_articles)}")

        # 更新分页锚点
        last_article = new_articles[-1]
        msgid = last_article.get("msgid")
        itemidx = last_article.get("itemidx")

    # 持久化存储
    with open("data.json", "w", encoding="utf-8") as f:
        json.dump(all_articles, f, ensure_ascii=False, indent=2)
    print(f"Total articles saved: {len(all_articles)}")

    def get_date(article):
        from datetime import datetime
        date = datetime.fromtimestamp(int(article['create_time'])).strftime('%Y-%m-%d')
        return date
    
    # [print(get_date(article)) for article in all_articles]

    [print(f"{get_date(article)} {article['title']}" ) for article in all_articles]

if __name__ == "__main__":
    fetch_wechat_articles()
